package com.kldy8.kldyw.filmfactory.FilmTalent;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.kldy8.kldyw.BaseAppCompatActivity;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.filmfactory.bean.City;
import com.kldy8.kldyw.filmfactory.bean.FilmTalent;
import com.kldy8.kldyw.filmfactory.bean.Positions;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.tools.widget.view.ExpandTabView;
import com.kldy8.kldyw.tools.widget.view.ViewLeft;
import com.kldy8.kldyw.tools.widget.view.ViewMiddle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 * 影视人才
 */
public class FilmTalentActivity extends BaseAppCompatActivity
{
    int position1,city1;
    int position2,city2;

    private List<Positions> positionsList1 = new ArrayList<Positions>();
    private List<City> cityList1 = new ArrayList<City>();

    private List<Positions> positionsList2 = new ArrayList<Positions>();
    private List<City> cityList2 = new ArrayList<City>();

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private Toolbar toolbar;
    private int page1 = 1;
    private int page2 = 1;
    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private View view1, view2;
   private XRefreshView  refreshView1,refreshView2;
    FilmTalentAdapter adapter1,adapter2;
    private List<View> mViewList = new ArrayList<>();//页卡视图集合

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_film_talent);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("影视人才");//设置主标题
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true
        // 有小箭头，并且图标可以点击
        actionBar.setDisplayShowHomeEnabled(false);

        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        initViewPage();
        initData();

        Intent intent =  getIntent();
        int item = intent.getIntExtra("item",0);
        mViewPager.setCurrentItem(item);

    }

    private void initData()
    {
        initPersonList(true,page1,0,0);
        initCompanyList(true,page2,0,0);
    }

    private void initPersonList(final boolean isInit,int page,int position,int city)
    {
        ServerApi.person_list("" + page, "" +position, "" +city, new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView1!=null)
                {
                    refreshView1.stopRefresh();
                    refreshView1.stopLoadMore();
                }
//                Toast.makeText(FilmTalentActivity.this,"系统错误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {

                Log.e("......",response.toString());
                Log.e("page1",""+page1);
                ArrayList<FilmTalent> filmTalentList1 = new ArrayList<FilmTalent>();

                JSONObject jsonObject = new JSONObject(response);
                if ("0".equals(jsonObject.optString("code")))
                {
                    page1++;
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONArray objectPositions = objectData.optJSONArray("positions");
                    JSONArray objectCities = objectData.optJSONArray("cities");
                    JSONArray objectList = objectData.optJSONArray("list");

                    if (isInit == true)
                    {
                        page1 = 2;
                    }

                    if (null != objectPositions && objectPositions.length()>0) {

                        for (int i = 0; i < objectPositions.length(); i++) {
                            JSONObject objectPosition = objectPositions.optJSONObject(i);
                            Positions positions = Positions.resolution(objectPosition);
                            if (positions != null) {
                                positionsList1.add(positions);
                            }
                        }
                    }
                    if (null != objectCities && objectCities.length()>0)
                    {
                        for (int i = 0; i < objectCities.length(); i++)
                        {
                            JSONObject objectCity = objectCities.optJSONObject(i);
                            City city = new City();
                            city.resolution(objectCity);
                            cityList1.add(city);
                        }
                    }

                    if (null != objectList && objectList.length()>0)
                    {
                        for (int i = 0;i<objectList.length();i++)
                        {
                            JSONObject object = objectList.optJSONObject(i);
                            FilmTalent filmTalent = FilmTalent.resolution(object);
                            if (filmTalent != null)
                            {
                                filmTalentList1.add(filmTalent);
                            }
                        }
                    }

                        adapter1.replaceOrAdd(isInit,filmTalentList1);
                        adapter1.notifyDataSetChanged();

                        initExpandView(1,positionsList1,cityList1);
                        initExpandVaule(1);
                        initExpandListener(1);
                }
                else  if ("11005".equals(jsonObject.optString("code")))
                {
                    Toast.makeText(FilmTalentActivity.this, "暂无数据", Toast.LENGTH_LONG).show();
                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(FilmTalentActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    FilmTalentActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }

                if (refreshView1!=null)
                {
                    refreshView1.stopRefresh();
                    refreshView1.stopLoadMore();
                }
            }
        });
    }

    private void initCompanyList(final boolean isInit,int page,int position,int city)
    {
        ServerApi.job_company_list("" + page, "" +position, "" +city, new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }
                Toast.makeText(FilmTalentActivity.this,getResources().getString(R.string.error_net),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("......",response.toString());
                Log.e("page2",""+page2);

//                mSwipeRefreshLayout2.setRefreshing(false);
                Log.e("......",response.toString());
                JSONObject jsonObject = new JSONObject(response);
                ArrayList<FilmTalent> filmTalentList2 = new ArrayList<FilmTalent>();
                if ("0".equals(jsonObject.optString("code")))
                {
                    page2++;

                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONArray objectPositions = objectData.optJSONArray("positions");
                    JSONArray objectCities = objectData.optJSONArray("cities");
                    JSONArray objectList = objectData.optJSONArray("list");


                    if (isInit == true)
                    {
                        page2 = 2;
                        filmTalentList2 = new ArrayList<FilmTalent>();
                    }

                    if (objectPositions != null && objectPositions.length()>0)
                    {
                        for (int i = 0; i < objectPositions.length(); i++)
                        {
                            JSONObject objectPosition = objectPositions.optJSONObject(i);
                            Positions positions = Positions.resolution(objectPosition);
                            if (positions != null) {
                                positionsList2.add(positions);
                            }

                        }
                    }

                    if (objectCities != null && objectCities.length()>0) {
                        for (int i = 0; i < objectCities.length(); i++) {
                            JSONObject objectCity = objectCities.optJSONObject(i);
                            City city = new City();
                            city.resolution(objectCity);
                            cityList2.add(city);
                        }
                    }

                    if (objectList != null && objectList.length()>0) {
                        for (int i = 0; i < objectList.length(); i++) {
                            JSONObject object = objectList.optJSONObject(i);
                            FilmTalent filmTalent = FilmTalent.resolution(object);
                            if (filmTalent != null) {
                                filmTalentList2.add(filmTalent);
                            }

                        }
                    }

                    adapter2.replaceOrAdd(isInit,filmTalentList2);
                    adapter2.notifyDataSetChanged();

                    initExpandView(2,positionsList2,cityList2);
                    initExpandVaule(2);
                    initExpandListener(2);
                }
                else  if ("10003".equals(jsonObject.optString("code")))
                {

                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(FilmTalentActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    FilmTalentActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }


                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }

            }
        });
    }

    private void initListView(View view)
    {
        ListView list_view = (ListView) view.findViewById(R.id.list_view);

        if (view == view1)
        {
            adapter1 = new FilmTalentAdapter(this, new ArrayList<FilmTalent>());
            list_view.setAdapter(adapter1);

            refreshView1 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView1.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView1.setPinnedTime(1000);
            refreshView1.setPullLoadEnable(true);
            refreshView1.setMoveForHorizontal(true);
            refreshView1.setAutoLoadMore(true);
            refreshView1.setEmptyView(R.layout.layout_emptyview);
            refreshView1.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView1.startRefresh();
                }
            });

            refreshView1.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

                @Override
                public void onRefresh() {
                    requestPeopleData();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    morePeopleData();
                }
            });
        }
        else
        {
            adapter2 = new FilmTalentAdapter(this, new ArrayList<FilmTalent>());
            list_view.setAdapter(adapter2);
            refreshView2 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView2.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView2.setPinnedTime(1000);
            refreshView2.setPullLoadEnable(true);
            refreshView2.setMoveForHorizontal(true);
            refreshView2.setAutoLoadMore(true);
            refreshView2.setEmptyView(R.layout.layout_emptyview);
            refreshView2.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView2.startRefresh();
                }
            });

            refreshView2.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

                @Override
                public void onRefresh() {
                    requestComData();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    moreComData();
                }
            });
        }
    }

    //刷新人才求职数据
    public void requestPeopleData()
    {
        initPersonList(true,1,position1,city1);
    }
    //添加人才求职数据
    public void morePeopleData()
    {
        initPersonList(false,page1,position1,city1);
    }


    //刷新人才招募数据
    public void requestComData()
    {
        initCompanyList(true,1,position2,city2);
    }
    //添加人才招募数据
    public void moreComData()
    {
        initCompanyList(false,page2,position2,city2);
    }


    private void initViewPage()
    {
        mInflater = LayoutInflater.from(this);
        view1 = mInflater.inflate(R.layout.view_film_talent, null);
        expandTabView1 = (ExpandTabView) view1.findViewById(R.id.expandtab_view);
        initListView(view1);

        view2 = mInflater.inflate(R.layout.view_film_talent, null);
        expandTabView2 = (ExpandTabView) view2.findViewById(R.id.expandtab_view);
        initListView(view2);


        //添加页卡视图
        mViewList.add(view1);
        mViewList.add(view2);

        //添加页卡标题
        mTitleList.add("人才求职");
        mTitleList.add("人才招募");

        mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));

        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器

    }


            //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter
    {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList)
        {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount()
        {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            View currentFocus = getCurrentFocus();
            if (currentFocus != null) {
                currentFocus.clearFocus();
            }
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return mTitleList.get(position);//页卡标题
        }

    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == android.R.id.home)
        {
            finish();
            return true ;
        }

        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_notbtn, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
//        {
//
//            public boolean onQueryTextSubmit(String query)
//            {
//                Log.e("tag",query);
//                Intent intent=new Intent(FilmTalentActivity.this,SearchActivity.class);  //方法1
//                Bundle bundle=new Bundle();
//                String[] languages=getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM,languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });
//
//
//
//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                Toast.makeText(FilmTalentActivity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item) {
//                Toast.makeText(FilmTalentActivity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

            private ExpandTabView expandTabView1;
            private ExpandTabView expandTabView2;

            private ArrayList<View> mViewArray1;
            private ArrayList<View> mViewArray2 ;

            private ViewLeft viewLeft,viewLeft2;
            private ViewMiddle viewMiddle,viewMiddle2;
            private ViewLeft viewRight,viewRight2;

            /**
             *
             * @param type 1为第一页 2为第二页
             * @param positionses
             * @param cities
             */
            private void initExpandView(int type,List<Positions> positionses,List<City> cities)
            {
                if (type == 1)
                {
                    viewLeft = new ViewLeft(this, positionses);
                    viewMiddle = new ViewMiddle(this, cities);
                    viewRight = new ViewLeft(this);
                }
                else if(type == 2)
                {
                    viewLeft2 = new ViewLeft(this, positionses);
                    viewMiddle2 = new ViewMiddle(this, cities);
                    viewRight2 = new ViewLeft(this);
                }
            }

            /**
             *
             * @param type 1为第一页 2为第二页
             */
            private void initExpandVaule(int type)
            {
                if (type == 1)
                {
                    if (expandTabView1!=null)
                    {
                        expandTabView1.removeAllViews();
                    }
                    mViewArray1 = new ArrayList<View>();
                    mViewArray1.add(viewLeft);
//                    mViewArray1.add(viewRight);
                    mViewArray1.add(viewMiddle);
                    ArrayList<String> mTextArray = new ArrayList<String>();
                    mTextArray.add("类型");
                    mTextArray.add("地区");
                    expandTabView1.setValue(mTextArray, mViewArray1);
                }
                else if(type == 2)
                {
                    if (expandTabView2!=null)
                    {
                        expandTabView2.removeAllViews();
                    }
                    mViewArray2 = new ArrayList<View>();
                    mViewArray2.add(viewLeft2);
//                    mViewArray2.add(viewRight2);
                    mViewArray2.add(viewMiddle2);
                    ArrayList<String> mTextArray = new ArrayList<String>();
                    mTextArray.add("类型");
//                    mTextArray.add("价格");
                    mTextArray.add("地区");
                    expandTabView2.setValue(mTextArray, mViewArray2);
                }



            }

            /**
             *
             * @param type 1为第一页 2为第二页
             */
            private void initExpandListener(int type)
            {
                if (type == 1)
                {
                    viewLeft.setOnSelectListener(new ViewLeft.OnSelectListener()
                    {
                        @Override
                        public void getValue(String distance, String showText)
                        {
                            onRefresh(expandTabView1,viewLeft, showText);
                        }

                        @Override
                        public void getValue(Positions positions, String showText)
                        {
                            if (positions != null)
                            {
                                position1 = positions.id;
                            }
                        }
                    });

                    viewMiddle.setOnSelectListener(new ViewMiddle.OnSelectListener()
                    {

                        @Override
                        public void getValue(String showText)
                        {
                            onRefresh(expandTabView1,viewMiddle, showText);
                        }

                        @Override
                        public void getValue(City.Son son)
                        {
                            if (son != null)
                            {
                                city1 = son.id;
                            }
                        }
                    });

                    viewRight.setOnSelectListener(new ViewLeft.OnSelectListener()
                    {
                        @Override
                        public void getValue(String distance, String showText)
                        {
                            onRefresh(expandTabView1,viewRight, showText);
                        }

                        @Override
                        public void getValue(Positions positions, String showText)
                        {
                            if (positions != null)
                            {
                                position1 = positions.id;
                            }
                        }
                    });
                }
                else if(type == 2)
                {
                    viewLeft2.setOnSelectListener(new ViewLeft.OnSelectListener()
                    {
                        @Override
                        public void getValue(String distance, String showText)
                        {
                            onRefresh(expandTabView2,viewLeft2, showText);
                        }

                        @Override
                        public void getValue(Positions positions, String showText)
                        {
                            if (positions != null)
                            {
                                position2 = positions.id;
                            }
                        }
                    });

                    viewMiddle2.setOnSelectListener(new ViewMiddle.OnSelectListener()
                    {

                        @Override
                        public void getValue(String showText)
                        {
                            onRefresh(expandTabView2,viewMiddle2, showText);
                        }

                        @Override
                        public void getValue(City.Son son)
                        {
                            if (son != null)
                            {
                                city2 = son.id;
                            }
                        }
                    });

                    viewRight2.setOnSelectListener(new ViewLeft.OnSelectListener()
                    {
                        @Override
                        public void getValue(String distance, String showText)
                        {
                            onRefresh(expandTabView2,viewRight2, showText);
                        }

                        @Override
                        public void getValue(Positions positions, String showText)
                        {
                            if (positions != null)
                            {
                                position2 = positions.id;
                            }
                        }
                    });
                }
            }

            private void onRefresh(ExpandTabView expandTabView,View view, String showText)
            {
                expandTabView.onPressBack();
                int position = getPositon(expandTabView,view);
                if (position >= 0 && !expandTabView.getTitle(position).equals(showText))
                {
                    expandTabView.setTitle(showText, position);
                }
                Toast.makeText(this, showText, Toast.LENGTH_SHORT).show();
            }

            private int getPositon(ExpandTabView expandTabView,View tView)
            {
                if (expandTabView == expandTabView1)
                {
                    for (int i = 0; i < mViewArray1.size(); i++) {
                        if (mViewArray1.get(i) == tView) {
                            return i;
                        }
                    }
                }
                else if (expandTabView == expandTabView2)
                {
                    for (int i = 0; i < mViewArray2.size(); i++)
                    {
                        if (mViewArray2.get(i) == tView)
                        {
                            return i;
                        }
                    }
                }
                return -1;
            }


}
